package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>管理员用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 登录校验
     *
     * @param paramMap
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //获取参数
        String name = paramMap.get("name");
        String password = paramMap.get("password");
        //参数非空校验
        if (StringUtils.isEmpty(name)|| StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或者密码错误！");
        }
        //登录名查询用户信息
        AdUser adUser = query().eq("name", name).one();
        if (null == adUser){
            throw new LeadNewsException("用户名或者密码错误！");
        }
        //密码校验Md5
        password += adUser.getSalt();
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //检验密码，不同报错
        if (!adUser.getPassword().equals(encryptedPwd)){
            throw new LeadNewsException("用户名或者密码错误！");
        }
        //检验通过，生成token令牌
        //String token = AppJwtUtil.createToken(adUser.getId().longValue());
        String token = AppJwtUtil.createToken(adUser.getId());
        adUser.setPassword(null);
        adUser.setSalt(null);
        //构建结果返回
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        result.put("user",adUser);
        return result;
    }
}
